import axios from "axios";
import { useTabManagerStore } from "@renderer/store/pinia/tabManager";
import {useSnackbarStore} from "@renderer/store/pinia/useSnackbarStore";
import { useViewManagerStore } from "@renderer/store/pinia/viewManager";
import { Config } from "@common/config";
import imgSocketIo from "@renderer/api/BaseSocketIo";

axios.defaults.baseURL = "http://localhost:8080";

const sendSocketIoMsg = (msg) => {
  // console.log("Sending message", JSON.stringify(msg));
  const tabStore = useTabManagerStore()
  const viewStore = useViewManagerStore()
  const activeTabId = tabStore.activeTabId;
  const activeViewId = viewStore.tabActiveViewIdObj[activeTabId].viewId;
  const activeViewMode = viewStore.tabActiveViewIdObj[activeTabId].viewMode;
  const groupId = viewStore.tabActiveViewIdObj[activeTabId].groupId;
  const content = {
    ...msg,
    viewId: activeViewId,
    groupId: groupId,
    viewMode:activeViewMode
  }
  if (Config.socketInMainThread){
    (window as any).api.sendSocketIoMsg(content);
  }else {
    imgSocketIo.sendMsg(content);
  }
};

const api = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 60 * 1000,
  headers: {
    'Content-Type': 'application/json',
  }
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
// 添加token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    console.log('请求开始:', config.url);

    return config;
  },
  (error) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    const snackBarStore = useSnackbarStore()
    const { data, code, message } = response.data;
    if (code === 0) {
      snackBarStore.showSnackbar(`错误，${message}`);
    }
    if (code === 1){

        response.data = data;
    }
    return response;
  },
  (error) => {
    let message = '网络错误';
    const snackBarStore = useSnackbarStore()
    if (error.response) {
      // 服务器响应错误
      const { status, data } = error.response;

      switch (status) {
        case 400:
          message = '请求参数错误';
          snackBarStore.showSnackbar(`错误，${data.message}`);

          break;
        case 401:
          message = '未授权，请重新登录';
          // 清除token并跳转登录页
          localStorage.removeItem('token');
          window.location.href = '/login';
          break;
        case 403:
          message = '拒绝访问';
          break;
        case 404:
          message = '请求资源不存在';
          break;
        case 500:
          message = '服务器内部错误';
          break;
        default:
          message = data?.message || `请求失败 (${status})`;
      }
    } else if (error.request) {
      // 网络错误
      message = '网络连接失败';
    }

    return {
      success: false,
      data: null,
      message: message
    };
  }
);

const postRequest = (url, data) => {
  return api.post(url, data);
}

export { axios, sendSocketIoMsg ,postRequest };
